'use strict';

const sudo = require('sudo-prompt');
const path = require('path');
const vscode = require('vscode');
const { Uri } = vscode;

const CNS_CMD = "cnscript.runFile";
const WNS_CMD = "wnscript.runFile";

const VSCODE_PATH = path.join(vscode.env.appRoot,  '..', '..', 'Code.exe');

const INSTALL_REG = [
    'cmd /c chcp 437 & reg add "HKCR\\VBXFile\\shell\\edit\\command" /ve /d "\\"' + VSCODE_PATH + '\\" \\"%%1\\"" /f', 
    'cmd /c chcp 437 & reg add "HKCR\\CSXFile\\shell\\edit\\command" /ve /d "\\"' + VSCODE_PATH + '\\" \\"%%1\\"" /f',
];

function runCmd(commands) {
    for (let cmd of commands) {
        console.log(cmd);
        sudo.exec(cmd, (error, stdout, stderr) => {
            if (error) {
                console.log(`Error: ${error.message}`);
            }
        });
    }
}

function runFile(strCmd) {
    let editor = null;
    if (vscode.window.activeTextEditor) {
        editor = vscode.window.activeTextEditor;
    } else if (vscode.window.visibleTextEditors.length > 0) {
        for (e of vscode.window.visibleTextEditors) {
            if (e.document.languageId === 'vbx' || e.document.languageId === 'csx') {
                editor = e;
                break;
            }
        }
        editor = vscode.window.visibleTextEditors[0];
    }
    if (!editor) return;

    const doc = editor.document;
    if (doc.languageId !== 'vbx' && doc.languageId !=='csx') return;

    const filePath = doc.fileName;

    let terminal = vscode.window.terminals.find(t => t.name === "Run NScript");
    if (!terminal) {
        terminal = vscode.window.createTerminal("Run NScript");
    }
    terminal.show();

    switch (strCmd) {
        case CNS_CMD:
            terminal.sendText(`cnscript "${filePath}"`);
            break;
        case WNS_CMD:
            terminal.sendText(`wnscript "${filePath}"`);
            break;
    }
    return;
}

function activate(context) {
    const init = context.globalState.get("init", true);
    if (process.platform === "win32" && init) {
        runCmd(INSTALL_REG);
        context.globalState.update("init", true);
    }

    const commands = [CNS_CMD, WNS_CMD];
    
    commands.forEach(cmd => {
        let disposable = vscode.commands.registerCommand(cmd, () => { runFile(cmd) });
        context.subscriptions.push(disposable);
    });

    let cmd = vscode.commands.registerCommand("nscript.gethelp", async () => {
        let editor = vscode.window.activeTextEditor;
        if (!editor) return;
        
        const selection = editor.selection;
        const document  = editor.document;

        let keyword = "";

        if (selection.isEmpty) {
            const wordRange = document.getWordRangeAtPosition(selection.active, /\w+/);

            if (wordRange) {
                keyword = document.getText(wordRange);
            } else {
                keyword = "";
            }
        } else {
            keyword = document.getText(selection);
        }
        
        if (keyword) {
            let url = "https://learn.microsoft.com/en-us/dotnet/api/?view=netframework-4.0&term=" + keyword;
            await vscode.commands.executeCommand("vscode.open", Uri.parse(url));   
        }
    });
    context.subscriptions.push(cmd);
}

module.exports = {
    activate,
};